<template>
  <el-container class="add">
    <el-row>
      <el-col :span="24" style="display: flex; align-items: center; justify-content: center">
        <p>在此页面，您可以{{ s }}场馆</p>
        <el-button type="primary" style="position: absolute; right: 10%" @click="back()">返回<el-icon color="write"
            class="no-inherit">
            <ArrowRight />
          </el-icon></el-button>
      </el-col>
    </el-row>
    <el-main class="main-1">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
        :size="formSize" status-icon>
        <el-form-item label="场馆名称" prop="name">
          <el-input v-model="ruleForm.name" style="width: 250px" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="ruleForm.phone" style="width: 250px" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-cascader v-model="value" :options="options" placeholder="请选择地址" @change="handleChange" />
          <!-- <el-input
            v-model="ruleForm.address"
            style="width: 250px"
            placeholder="请输入地址"
          /> -->
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" style="width: 250px" />
        </el-form-item>
        <el-form-item label="受众人群" prop="type">
          <el-checkbox-group v-model="ruleForm.type">
            <el-checkbox label="青年" name="type" />
            <el-checkbox label="中年" name="type" />
            <el-checkbox label="老年" name="type" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio label="可预约" />
            <el-radio label="已预约" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片上传" prop="coachImageId">
          <el-upload action="#" list-type="picture-card" :auto-upload="false">
            <el-icon>
              <Plus />
            </el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="介绍" prop="introduce">
          <el-input v-model="ruleForm.introduce" type="textarea" style="width: 500px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :plain="true" @click="submitForm(ruleFormRef)">保存</el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-main>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>

    <el-dialog v-model="dialogVisible1" title="提示" width="30%" :before-close="handleClose">
      <span>您有修改仍未保存，是否确认返回</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="confirm"> 确认返回 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, onBeforeMount, defineExpose } from "vue";
import { useRouter, useRoute } from "vue-router";
import type { FormInstance, FormRules, UploadFile } from "element-plus";
import { ArrowRight, Delete, Plus, ZoomIn } from "@element-plus/icons-vue";
import { checkMobile, checkEmail, checkName } from "./function/regexRules";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  searchVenues,
  addVenues,
  uploadPicture,
  updateVenues,
} from "../../http/api";
import mitts from "./mitt";

const route = useRoute();
const router = useRouter();
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);

const s = route.query.msg;
const zid = route.query.id;
const formSize = ref("default");
const dialogVisible1 = ref(false);
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  address: "",
  coachImageId: [
    {
      imageUrl: "",
    },
  ],
  id: 0,
  email: "",
  introduce: "",
  isDefaultVenue: 0,
  name: "",
  phone: "",
  status: "",
  venueFieldList: [
    {
      id: 0,
      createTime: "",
      isDeleted: 0,
      name: "",
      purpose: 0,
      updateTime: "",
      venueCapacity: "",
      venueId: 0,
    },
  ],
});
let msg = ref();
let state = reactive({
  test: [],
  msg,
});
const options = [
  {
    value: "上海市",
    label: "上海市",
    children: [
      {
        value: "静安区",
        label: "静安区",
        children: [
          {
            value: "安寺街道",
            label: "安寺街道",
          },
          {
            value: "曹家渡街道",
            label: "曹家渡街道",
          },
          {
            value: "江宁路街道",
            label: "江宁路街道",
          },
        ],
      },
      {
        value: "黄浦区",
        label: "黄浦区",
        children: [
          {
            value: "外滩街道",
            label: "外滩街道",
          },
          {
            value: "老西门街道",
            label: "老西门街道",
          },
        ],
      },
    ],
  },
  {
    value: "北京市",
    label: "北京市",
    children: [
      {
        value: "朝阳区",
        label: "朝阳区",
        children: [
          {
            value: "朝外街道",
            label: "朝外街道",
          },
          {
            value: "劲松街道",
            label: "劲松街道",
          },
        ],
      },
      {
        value: "西城区",
        label: "西城区",
        children: [
          {
            value: "金融街街道",
            label: "金融街街道",
          },
        ],
      },
      {
        value: "海淀区",
        label: "海淀区",
        children: [
          {
            value: "万寿路街道",
            label: "万寿路街道",
          },
          {
            value: "永定路街道",
            label: "永定路街道",
          },
          {
            value: "圆明园遗址公园",
            label: "圆明园遗址公园",
          },
        ],
      },
    ],
  },
  {
    value: "深圳市",
    label: "深圳市",
    children: [
      {
        value: "南山区",
        label: "南山区",
      },
      {
        value: "福田区",
        label: "福田区",
      },
      {
        value: "盐田区",
        label: "盐田区",
      },
    ],
  },
];
const rules = reactive<FormRules>({
  name: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { trigger: "blur", validator: checkName },
  ],
  phone: [
    { required: true, message: "请输入电话号码", trigger: "blur" },
    { trigger: "blur", validator: checkMobile },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { trigger: "blur", validator: checkEmail },
  ],
  type: [
    {
      type: "array",
      trigger: "change",
    },
  ],
  resource: [
    {
      required: true,
      message: "请确认场地状态",
      trigger: "change",
    },
  ],
  introduce: [{ trigger: "blur" }],
});
const handleChange = (value) => {
  let a = "";
  value.forEach((el) => {
    a += el;
  });
  console.log(a);
  ruleForm.address = a;
};

onMounted(() => {
  // mitts.on("msg", (e) => {
  //   msg.value = e;
  //   console.log(e);
  // });{}
  if (s == "编辑") {
    searchVenues({ id: zid }).then((res) => {
      console.log(res.data);
      state.test = res.data;
      ruleForm.name = res.data.name;
      ruleForm.phone = res.data.phone;
      ruleForm.email = res.data.email;
      ruleForm.status = res.data.status;
      ruleForm.introduce = res.data.introduce;
      ruleForm.id = zid;
    });
  }
});

// 返回上一级
const show = () => {
  dialogVisible1.value = true;
};
const confirm = () => {
  dialogVisible1.value = false;
  router.push({ path: "ListVenues" });
};
const back = () => {
  if (s == "编辑") {
    if (
      state.test.name != ruleForm.name ||
      state.test.phone != ruleForm.phone ||
      state.test.email != ruleForm.email ||
      state.test.status != ruleForm.status
    ) {
      show();
    } else {
      router.push({ path: "ListVenues" });
    }
  } else {
    console.log(ruleForm);
    if (
      ruleForm.name != "" ||
      ruleForm.phone != "" ||
      ruleForm.email != "" ||
      ruleForm.status != ""
    ) {
      show();
    } else {
      router.push({ path: "ListVenues" });
    }
  }
};
const handleClose = (done: () => void) => {
  ElMessageBox.confirm("是否关闭")
    .then(() => {
      done();
    })
    .catch(() => { });
};

// 图像上传
// const fileList = ref<UploadUserFile[]>([]);
// const handleRemove = (file: UploadFile) => {
//   console.log(file);
// };
const handleRemove = (file: UploadFile) => {
  console.log(file);

  // 1.获取将要删除图片的临时路径
  // const filePath = file.response.data.tmp_path;
  // // 2.从pics数组中，找到图片对应的索引值
  // const i = this.addForm.pics.findIndex((x) => x.pic === filePath);
  // // 3.调用splice方法，移除图片信息
  // this.addForm.pics.splice(i, 1);
};
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};

// 提交数据
const submitForm = async (formEl: FormInstance | undefined) => {
  if (s == "编辑") {
    // updateVenues({ venueAddDto: ruleForm }).then((res) => {
    //   console.log(res);
    // });
    console.log(ruleForm);
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        updateVenues(ruleForm).then((res) => {
          if (res.code == 0) {
            ElMessage({
              message: "修改成功",
              type: "success",
              duration: 1000,
            });
            setTimeout(() => {
              router.push("ListVenues");
            }, 1500);
          }
        });
      }
    });
  } else {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log(ruleForm);
        addVenues(ruleForm).then((res) => {
          console.log(res);
          if (res.code == 0) {
            ElMessage({
              message: "新增成功",
              type: "success",
              duration: 1000,
            });
            setTimeout(() => {
              router.push({ path: "ListVenues" });
            }, 1500);
          }
        });
      }
    });
  }
};
// 取消提交
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push("ListVenues");
};
</script>

<style scoped>
.add {
  margin-left: 10px;
  background-color: rgba(242, 242, 242, 1);
  display: flex;
  flex-direction: column;
  border-radius: 20px;
}

.main-1 {
  background-color: white;
  margin: 0 50px 50px 50px;
  border-radius: 20px;
}
</style>
